package com.xbjtech.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.model.Resource;
import com.xbjtech.model.Role;
import com.xbjtech.model.User;
import com.xbjtech.service.UserService;

import tk.mybatis.mapper.entity.Example;

public class CustomRealm extends AuthorizingRealm {

	@Autowired
	UserService userService;
	
	/**
	 * 收集授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		this.clearCachedAuthorizationInfo(principals);
		
		User user = (User) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 权限信息
		// 添加角色
		// info.addRole("")
		// 添加权限=>别名
		// info.addStringPermission("")
		// info.addObjectPermission(permission);
		Integer uid = user.getId();
		user = userService.selectUsersRoleAndResource(uid);
		if (null != user) {
			for (Role r : user.getRoles()) {
				info.addRole(r.getCode());
				for (Resource res : r.getReses()) {
					String code = res.getCode();
					if (!"".equals(code)) {
						info.addStringPermission(res.getCode());
					}
				}
			}
		}
		return info;
	}

	/**
	 * 收集正确认证信息{这个认证信息一般情况下，是从数据库里面取出来}
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken t = (UsernamePasswordToken) token;
		String username = t.getUsername();
		Example ex = new Example(User.class);
		ex.createCriteria().andEqualTo("username", username);
		List<User> list = userService.selectByExample(ex);
		if (null == list || list.size() == 0 || list.get(0) == null) {
			throw new UnknownAccountException("用户名不存在");
		}
		User user = list.get(0);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(),
				ByteSource.Util.bytes(user.getId() + ""), getName());
		return info;
	}
	
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

}
